import { ERROR_LOG_ROUTE } from '@/router/constants';
import { LINK_HOME } from '@/router/constants';
import { asyncRoutes } from '@/router';
import { defineStore } from 'pinia';
import { joinParentAttr, joinSubMenuIndex } from 'vc/src/router';
import type { RouteRecordItem, MenuType } from 'vc/src/router';
import pinia from '../';

interface PermissionState {
  /** 路由是否已动态添加 */
  isDynamicAddedRoute: boolean;
  // 前端菜单列表
  menuList: MenuType[];
}

/**
 * @description 权限的全局状态管理
 * @author wfd
 * @date 2021-07-12 15:10:07
 */
export const usePermissionStore = defineStore({
  id: 'app-permission',
  persist: {
    strategies: [
      {
        paths: ['menuList']
      }
    ]
  },
  state: (): PermissionState => ({
    isDynamicAddedRoute: false,
    menuList: []
  }),
  getters: {
    getMenuList(): MenuType[] {
      return this.menuList;
    },
    getIsDynamicAddedRoute(): boolean {
      return this.isDynamicAddedRoute;
    }
  },
  actions: {
    setMenuList(list: MenuType[]) {
      this.menuList = list;
    },
    setDynamicAddedRoute(added: boolean) {
      this.isDynamicAddedRoute = added;
    },
    resetState(): void {
      this.isDynamicAddedRoute = false;
      this.menuList = [];
    },
    async buildRoutesAction(): Promise<RouteRecordItem[]> {
      const routes: RouteRecordItem[] = asyncRoutes;
      
      const patchHomeAffix = (routes: RouteRecordItem[]) => {
        if (!routes || routes.length === 0) return;
        let homePath: string = LINK_HOME;
        
        function patcher(routes: RouteRecordItem[], parentPath = '') {
          if (parentPath) parentPath = parentPath + '/';
          routes.forEach((route: RouteRecordItem) => {
            const { path, children, redirect } = route;
            const currentPath = path.startsWith('/') ? path : parentPath + path;
            if (currentPath === homePath) {
              if (redirect) {
                homePath = route.redirect! as string;
              } else {
                route.meta = Object.assign({}, route.meta, { affix: true });
                throw new Error('end');
              }
            }
            children && children.length > 0 && patcher(children, currentPath);
          });
        }
        
        try {
          patcher(routes);
        } catch (e) {
        }
        return;
      };
      
      
      joinParentAttr(routes);
      joinSubMenuIndex(routes);
      
      routes.push(ERROR_LOG_ROUTE);
      
      patchHomeAffix(routes);
      return routes;
    }
  }
});

export function usePermissionStoreWithOut() {
  return usePermissionStore(pinia);
}
